package tr.edu.metu.is.mega.server.service;

import java.util.List;

import tr.edu.metu.is.mega.client.service.GwtUserService;
import tr.edu.metu.is.mega.common.dto.UserDTO;
import tr.edu.metu.is.mega.server.business.UserManager;
import tr.edu.metu.is.mega.server.core.PagedQueryParams;
import tr.edu.metu.is.mega.server.core.SortDirection;

import com.extjs.gxt.ui.client.Style.SortDir;
import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * Implementation of GWT user service.
 */
public class GwtUserServiceImpl extends RemoteServiceServlet implements GwtUserService {

    private static final long serialVersionUID = -9083785881491659422L;

    private UserManager manager = null;

    /**
     * Default constructor.
     */
    public GwtUserServiceImpl() {
        manager = new UserManager();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UserDTO login(String userid, String password) {
        return manager.login(userid, password);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public PagingLoadResult<UserDTO> getUsers(PagingLoadConfig config, UserDTO filter) {
        List<UserDTO> list = manager.getUsers(toPagedQueryParams(config), filter);
        int userCount = manager.getUserCount(filter).intValue();
        return new BasePagingLoadResult<UserDTO>(list, config.getOffset(), userCount);
    }

    /**
     * Converts paging load config parameters to paged query parameters.
     * 
     * @param config load config
     * @return query params
     */
    private PagedQueryParams toPagedQueryParams(PagingLoadConfig config) {
        PagedQueryParams params = new PagedQueryParams();
        params.setFirstResult(config.getOffset());
        params.setMaxResults(config.getLimit());
        if (config.getSortInfo().getSortField() != null) {
            String sortField = config.getSortInfo().getSortField();
            params.setSortField(sortField);
            if (config.getSortInfo().getSortDir() == SortDir.ASC) {
                params.setDirection(SortDirection.ASC);
            } else {
                params.setDirection(SortDirection.DESC);
            }
        }
        return params;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UserDTO updateUser(UserDTO user) {
        return manager.updateUser(user);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UserDTO createUser(UserDTO user) {
        return manager.createUser(user);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void deleteUser(UserDTO user) {
        manager.deleteUser(user);
    }

}
